<?php
/**
 * 列表参数基础类
 *
 * @author: WangBin
 * @date: 2021/7/26
 * @mail: <849850352@qq.com>
 */

namespace App\Params;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Traits\VerifyRequestParam;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class Param
{
    use VerifyRequestParam;

    /**
     * 填充参数
     *
     * @return $this
     * @throws
     */
    public function fill()
    {
        $rules = $this->rules();
        // 获取所有参数
        $data = request()->input();
        // 校验参数
        $validator = Validator::make($data, $rules);
        if($validator->fails()) {
            $validatorMsg = $validator->getMessageBag()->getMessages();
            $errorMsg = $validatorMsg[array_keys($validatorMsg)[0]][0];
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => $errorMsg]);
        }
        // 动态赋值
        collect($data)->map(function ($val, $key) {
            if(property_exists($this, $key)) {
                $this->{$key} = $val;
            }
        });

        return $this;
    }

    /**
     * 创建参数对象
     *
     * @return Param|static
     */
    public static function create()
    {
        return (new static())->fill();
    }

    /**
     * 参数校验规则
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

    /**
     * 转换为数组
     *
     * @return array $arr
     */
    public function toArray()
    {
        $arr = [];
        foreach ($this as $field => $value) {
            if(property_exists($this, $field)) {
                $arr[$field] = $value;
            }
        }
        return $arr;
    }
}
